<template>
  <div class="view_page" style="min-height: calc(100% - 20px);">
    <!--  新增/修改  -->
    <el-card class="box-card" v-loading="loading" element-loading-text="拼命加载中"
             element-loading-spinner="el-icon-loading"
             element-loading-background="rgba(0, 0, 0, 0.8)"
             style="min-height: 100%;">
      <!--卡片头部-->
      <div slot="header" class="clearfix">
        <!--左侧-->
        <div class="left">
          <div class="back-page">
            <div class="add-back" @click="back">
              <i class="fa fa-arrow-left" aria-hidden="true"></i>
              <span>
                更新设备配置
              </span>
            </div>
          </div>
        </div>
        <div class="right" v-if="addtype!='query'">
          <el-button type="primary" @click="submitAdd">保存</el-button>
        </div>
      </div>
      <!--卡片内容-->
      <div class="card-centont">
        <el-form :model="detail_data" label-width="150px">
          <div v-for="(item,index) in formAddItemList" :key="index">
            <el-form-item
              v-if="item.type=='string'||item.type=='decimal'||item.type=='number'"
              :label="item.label">
              <el-input
                v-model="detail_data[item.key]"
                :placeholder="item.placeholder"
                clearable
                :type="item.type=='decimal'?'number':item.type"
                @input="(item.type=='decimal'||item.type=='number')?checkFormatNumFixed2(item.key,item.decimal_number):null"
                @blur="(item.type=='decimal'||item.type=='number')?tt(item.key):null"
                @mousewheel.native.prevent
                @DOMMouseScroll.native.prevent
                :disabled="addtype=='query'||item.isDisable"
              ></el-input>
            </el-form-item>
            <el-form-item v-if="item.type=='textarea'" :label="item.label">
              <el-input v-model="detail_data[item.key]"
                        :placeholder="item.placeholder"
                        :type="item.type"
                        :disabled="addtype=='query'"
              ></el-input>
            </el-form-item>
            <el-form-item v-if="item.type=='switch'" :label="item.label">
              <el-switch v-model="detail_data[item.key]"
                         :disabled="addtype=='query'"
              ></el-switch>
            </el-form-item>

            <div v-if="item.type=='list'&&item.key=='monitor_list'">
              <monitor-setting-list :label-name="item.label"
                                    :default-select-arr="monitorSelectArr"
                                    :default-table-arr="selectedMonitorList"
                                    :is-warning="true"
                                    :is-drag-sort="true"
                                    @updateTableList="updateTableMonitorList"
                                    @updateSelectedList="updateSelectedMonitorList"
              ></monitor-setting-list>
            </div>
          </div>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
  import {
    Message
  } from 'element-ui';
  import Utils from '@/utils/index.js';
  import Sortable from 'sortablejs';
  import MonitorSettingList from '../components/monitor-setting-list';

  export default {
    name: 'MonitorDeviceAdd',
    components: {
      MonitorSettingList,
    },
    data() {
      return {
        from: '',
        loading: false,
        formAddItemList: [
          {
            key: 'monitor_list',
            label: '选择测点(多选)',
            placeholder: '',
            type: 'list',
            // decimal_number: 2,
            isDisable: false,
            monitor_list: [],
          },
        ],
        addtype: 'add',
        initDetailData: {},
        detail_data: {
          id: -1,
        },
        monitorSelectArr: [],
        selectedMonitorList: [],
        monitorOptions: [],
        river_type: -1,
        river_id: -1,
        device_id: '',
        real_type: 1,
      }
    },
    mounted() {
      for (let i = 0; i < this.formAddItemList.length; i++) {
        let key_str = this.formAddItemList[i].key;
        if (this.detail_data[key_str] == undefined) {
          this.$set(this.detail_data, key_str, '');
        }
      }
      this.$set(this.detail_data, 'monitor_arr', []);
      this.initDetailData = this.detail_data;
    },
    created() {
      this.addtype = this.$route.query.type || 'add';
      this.river_type = this.$route.query.river_type || -1;
      this.real_type = this.$route.query.real_type || 1;
      this.river_id = this.$route.query.river_id || -1;
      this.device_id = this.$route.query.device_id || '';
      let device_list = this.$route.query.device_list || [];
      this.getAllSelectList();

      let initMonitorList = (list) => {
        let dataIds = [], dataArr = [];
        for (let i = 0; i < list.length; i++) {
          let tt = list[i];
          let idObj = [];
          if (this.real_type==4){
            idObj.push(tt.river_type);
            idObj.push(tt.river_id);
            idObj.push(tt.device_id);
            idObj.push(tt.monitor_id);
          }else if (this.real_type==5){
            idObj.push(tt.river_type);
            idObj.push(tt.river_id);
            idObj.push(tt.device_id);
            idObj.push(tt.monitor_id);
          }
          dataIds.push(idObj);
          let itemObj = {
            "river_type": tt.river_type,
            "river_id": tt.river_id,
          };
          if (this.real_type==4){
            Object.assign(itemObj,{
              "device_id": tt.equipment,
              "monitor_id": parseInt(tt.device_checkpoint),
              "name": tt.name,
              "id": parseInt(tt.device_checkpoint),
              "monitor_num": tt.device_checkpoint_name,
            });
          }else if (this.real_type==5){
            Object.assign(itemObj,{
              "device_id": tt.equipment,
              "monitor_id": parseInt(tt.device_checkpoint),
              "name": tt.name,
              "id": parseInt(tt.device_checkpoint),
              "monitor_num": tt.device_checkpoint_name,
            });
          }
          dataArr.push(itemObj);
        }
        this.monitorSelectArr = dataIds;
        this.selectedMonitorList = dataArr;
        console.log(JSON.stringify(this.monitorSelectArr))
        console.log(JSON.stringify(this.selectedMonitorList))
      };

      if (this.real_type == 4) {
        if (this.addtype == "add") {
        }
        if (this.addtype == 'update' || this.addtype == 'query') {
          let data = this.$route.query.data;
          this.detail_data = data || this.initDetailData;
          initMonitorList(device_list);
        }
      } else if (this.real_type == 5) {
        initMonitorList(device_list);
      }
    },
    methods: {
      getAllSelectList() {
        let data = {};
        this.$apis.unity_monitor_set_all(data).then(res => {
          if (res.result == 0) {
            this.monitorOptions = res.data;
          }
        });
      },
      updateTableMonitorList(params) {
        this.selectedMonitorList = params || [];
      },
      updateSelectedMonitorList(params) {
        this.monitorSelectArr = params || [];
      },
      checkFormatNumFixed2(key, decimal_number) {
        if (this.detail_data[key] == 0 || this.detail_data[key] == '') {
          return
        }
        let regx = /^()*(\d+)\.(\d\d).*$/;
        if (typeof decimal_number != "number") {
          decimal_number = 2;
          regx = /^()*(\d+)\.(\d\d).*$/;
        } else {
          if (decimal_number == -1) {
            decimal_number = 9999;
            regx = /^()*(\d+)\.(\d{9999}).*$/;
          } else if (decimal_number == 0) {
            decimal_number = 0;
            regx = /[^\d]/g;
            this.detail_data[key] = (this.detail_data[key]).replace(regx, '');
            this.detail_data[key] = parseFloat(this.detail_data[key]);
            return;
          } else {
            decimal_number = 2;
            regx = /^()*(\d+)\.(\d\d).*$/;
          }
        }
        let checkPlan = "" + this.detail_data[key];
        checkPlan = checkPlan.replace(/[^\d.]/g, "") // 清除“数字”和“.”以外的字符
        .replace(/\.{2,}/g, ".") // 只保留第一个. 清除多余的
        .replace(/^\./g, "") // 保证第一个为数字而不是.
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
        if (checkPlan.indexOf(".") < 0 && checkPlan !== "") {
          // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
          checkPlan = parseFloat(checkPlan) + "";
        } else if (checkPlan.indexOf(".") >= 0) {
          checkPlan = checkPlan.replace(regx, "$1$2.$3"); // 只能输入两个小数
        }
        if (checkPlan > 1) {
          checkPlan = checkPlan
          .replace(/^0*/g, "") // 清除数字之前的0
        } else {
          checkPlan = checkPlan
          .replace(/^0*/g, "0") // 清除数字之前的0
        }
        this.detail_data[key] = checkPlan;
        this.detail_data[key] = parseFloat(this.detail_data[key]);
      },
      tt(key_str) {
        if (this.detail_data[key_str] != '') {
          this.detail_data[key_str] = parseFloat(this.detail_data[key_str])
        }
      },
      submitAdd() {
        let rList = [];
        for (let i = 0; i < this.selectedMonitorList.length; i++) {
          let tt = this.selectedMonitorList[i];
          let tp = {
            name: tt.name,
            tb_device_checkpoint: tt.id,
            river_type: tt.river_type,
            river_id: tt.river_id,
            device_id: tt.device_id,
            monitor_id: tt.monitor_id,
          };
          rList.push(tp);
        }
        if (rList.length == 0) {
          Message.warning('请选择测点')
          return
        }
        let params = {};
        // let params = {
        //   equipment: typeof this.device_id == "string" ? parseInt(
        //     this.device_id) : this.device_id,
        //   array: JSON.stringify(rList),
        // };
        // console.log(JSON.stringify(this.selectedMonitorList))
        // console.log(JSON.stringify(params))
        console.log(this.real_type)
        console.log(rList)

        if (this.real_type == 4) {
          // 设备
          Object.assign(params, {
            equipment: typeof this.device_id == "string" ? parseInt(
              this.device_id) : this.device_id,
            array: JSON.stringify(rList),
          });
          if (this.addtype == 'add') {
            this.$apis.unity_monitor_device_add(params).then(res => {
              if (res.result == 0) {
                Message.success('添加成功')
                this.$router.back()
              }
            });
          } else if (this.addtype == 'update') {
            let params_reset = {
              equipment: this.device_id,
            };
            this.$apis.unity_monitor_device_reset(params_reset).then(res => {
              if (res.result == 0) {
                this.$apis.unity_monitor_device_add(params).then(res => {
                  if (res.result == 0) {
                    Message.success('修改成功')
                    this.$router.back()
                  }
                });

              }
            });

            // this.$apis.unity_monitor_device_update(params).then(res => {
            //   if (res.result == 0) {
            //     Message.success('修改成功')
            //     this.$router.back()
            //   }
            // });
          }
        } else if (this.real_type == 5) {
          // 站点
          Object.assign(params, {
            id: typeof this.device_id == "string" ? parseInt(
              this.device_id) : this.device_id,
            json: JSON.stringify(rList),
          });
          console.log('site config update===', params)
          this.$apis.v2_safe_config_update(params).then(res => {
            if (res.result == 0) {
              Message.success('更新配置成功')
              this.$router.back()
            }
          });
        }
      },
      back() {
        this.$router.back()
      },
    }
  }
</script>

<style>

</style>
